<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|consolas:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="干货,Git," />





  <link rel="alternate" href="/atom.xml" title="🐕 @Leeifme" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="工作区和版本库 工作区： 就是你电脑文件夹能看到的目录，就如我创建的test文件夹就是一个工作区 1234&amp;gt;  leeif@leeif MINGW64 /e/git/test (master)&amp;gt;  $ ls&amp;gt;  git.txt  index.html  README.md&amp;gt;  版本库(Repository)： 工作区有一个隐藏的目录文件.git，这个虽然在工作区目录下，但">
<meta name="keywords" content="干货,Git">
<meta property="og:type" content="article">
<meta property="og:title" content="Git实践-修改操作">
<meta property="og:url" content="http://www.leeif.me/technology/other/Git实践-修改操作/index.html">
<meta property="og:site_name" content="🐕 @Leeifme">
<meta property="og:description" content="工作区和版本库 工作区： 就是你电脑文件夹能看到的目录，就如我创建的test文件夹就是一个工作区 1234&amp;gt;  leeif@leeif MINGW64 /e/git/test (master)&amp;gt;  $ ls&amp;gt;  git.txt  index.html  README.md&amp;gt;  版本库(Repository)： 工作区有一个隐藏的目录文件.git，这个虽然在工作区目录下，但">
<meta property="og:image" content="http://orj2jcr7i.bkt.clouddn.com/%E5%B7%A5%E4%BD%9C%E5%8C%BA%E5%92%8C%E7%89%88%E6%9C%AC%E5%BA%93.png">
<meta property="og:image" content="http://orj2jcr7i.bkt.clouddn.com/git%20add.png">
<meta property="og:image" content="http://orj2jcr7i.bkt.clouddn.com/git%20commit.png">
<meta property="og:updated_time" content="2017-06-27T14:19:10.895Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Git实践-修改操作">
<meta name="twitter:description" content="工作区和版本库 工作区： 就是你电脑文件夹能看到的目录，就如我创建的test文件夹就是一个工作区 1234&amp;gt;  leeif@leeif MINGW64 /e/git/test (master)&amp;gt;  $ ls&amp;gt;  git.txt  index.html  README.md&amp;gt;  版本库(Repository)： 工作区有一个隐藏的目录文件.git，这个虽然在工作区目录下，但">
<meta name="twitter:image" content="http://orj2jcr7i.bkt.clouddn.com/%E5%B7%A5%E4%BD%9C%E5%8C%BA%E5%92%8C%E7%89%88%E6%9C%AC%E5%BA%93.png">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: undefined,
      author: 'Author'
    }
  };
</script>




  <link rel="canonical" href="http://www.leeif.me/technology/other/Git实践-修改操作/"/>

  <title> Git实践-修改操作 | 🐕 @Leeifme </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>
    
    <header id="header_post" class="header" itemscope itemtype="http://schema.org/WPHeader" style="background-image: url('http://ortur5wom.bkt.clouddn.com/cover-bash.jpg');">
      <div class="header-inner-post"><a class="site-home" href="/">🐕 @Leeifme</a>

<div class="site-meta custom-logo">
  
  
  
    <div class="site-meta-headline">
      <a>
        <img class="custom-logo-image" src="/images/logo.png" style="width: 80px"
             alt="🐕 @Leeifme"/>
      </a>
    </div>
  

  
  
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        
        
           <li class="menu-item menu-item-about">
             <a href="/about" rel="section">
               
                 <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
               
               
               about
             </a>
           </li>
        
      
        
        
        
           <li class="menu-item menu-item-movie">
             <a href="/movie" rel="section">
               
                 <i class="menu-item-icon fa fa-fw fa-superscript"></i> <br />
               
               
               movie
             </a>
           </li>
        
      
        
        
        
           <li class="menu-item menu-item-coding">
             <a href="/categories/coding" rel="section">
               
                 <i class="menu-item-icon fa fa-fw fa-cogs"></i> <br />
               
               
               coding
             </a>
           </li>
        
      
        
        
        
           <li class="menu-item menu-item-archives">
             <a href="/archives" rel="section">
               
                 <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
               
               
               archives
             </a>
           </li>
        
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <input type="text" id="local-search-input">
 <span class="search-icon fa fa-search"></span>
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
      <div class="header-post"> 
  <div class="post-header">
      <div class="tags">
      
        <a href="/tags/干货/" rel="tag" title="干货">干货</a>
      
        <a href="/tags/Git/" rel="tag" title="Git">Git</a>
      
      </div>
      <h1>Git实践-修改操作</h1>
      <h2 class="subtitle"></h2>
      <div class="post-time">
        <span class="post-meta-item-text">Posted on </span>
        <time itemprop="dateCreated" datetime="2017-06-11T20:36:25+08:00" content="2017-06-11" title="2017-06-11 20:36:25">
          2017-06-11
        </time>
      </div>
  </div>
 </div>
    </header>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Git实践-修改操作
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2017-06-11T20:36:25+08:00" content="2017-06-11">
              2017-06-11
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/technology/" itemprop="url" rel="index">
                    <span itemprop="name">technology</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/technology/other/" itemprop="url" rel="index">
                    <span itemprop="name">other</span>
                  </a>
                </span>

                
                

              
            </span>
          

          <!-- 
            
           -->

          

          
          
             <span id="/technology/other/Git实践-修改操作/" class="leancloud_visitors" data-flag-title="Git实践-修改操作">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv"><i class="fa fa-eye"> </i>
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <link rel="stylesheet" type="text/css" href="/assets/css/DPlayer.min.css"><script src="/assets/js/DPlayer.min.js"> </script><script src="/assets/js/APlayer.min.js"> </script><blockquote>
<h2 id="工作区和版本库"><a href="#工作区和版本库" class="headerlink" title="工作区和版本库"></a>工作区和版本库</h2><ul>
<li><p><strong>工作区：</strong></p>
<p>就是你电脑文件夹能看到的目录，就如我创建的test文件夹就是一个工作区</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">&gt;  leeif@leeif MINGW64 /e/git/test (master)</div><div class="line">&gt;  $ ls</div><div class="line">&gt;  git.txt  index.html  README.md</div><div class="line">&gt;</div></pre></td></tr></table></figure>
</li>
<li><p><strong>版本库(Repository)：</strong></p>
<p>工作区有一个隐藏的目录文件<code>.git</code>，这个虽然在工作区目录下，但不算在工作区，而是<code>Git</code>的版本库。</p>
<p><code>Git</code>的版本库里存了很多东西，其中最重要的就是称为stage（或者叫index）的暂存区，还有Git为我们自动创建的第一个分支<code>master</code>，以及指向<code>master</code>的一个指针叫<code>HEAD</code>。</p>
<p><img src="http://orj2jcr7i.bkt.clouddn.com/%E5%B7%A5%E4%BD%9C%E5%8C%BA%E5%92%8C%E7%89%88%E6%9C%AC%E5%BA%93.png" alt="flex-axis"></p>
</li>
</ul>
<p> ​</p>
<p>上一篇讲了我们把文件往Git版本库里添加的时候，是分两步执行的：</p>
<ol>
<li>用<code>git add</code>把文件添加进去，实际上就是把文件修改添加到暂存区；</li>
<li>用<code>git commit</code>提交更改，实际上就是把暂存区的所有内容提交到当前分支。</li>
</ol>
<p>因为我们创建Git版本库时，Git自动为我们创建了唯一一个<code>master</code>分支，所以，现在，<code>git commit</code>就是往<code>master</code>分支上提交更改。</p>
<p>你可以简单理解为，需要提交的文件修改通通放到暂存区，然后，一次性提交暂存区的所有修改。</p>
<p><strong>ok，我们实践一下：</strong></p>
</blockquote>
<a id="more"></a>
<ul>
<li><p>首先新建一个文件<code>test.txt</code>，然后对<code>git.exe</code>进行修改，</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">$ git diff git.txt</div><div class="line">diff --git a/git.txt b/git.txt</div><div class="line">index 97fe984..a537f08 100644</div><div class="line">--- a/git.txt</div><div class="line">+++ b/git.txt</div><div class="line">@@ -2,4 +2,6 @@ Git is a version control system.</div><div class="line"> Git is free software.</div><div class="line"></div><div class="line"> Git is a distributed version control system.</div><div class="line">-Git is free software.</div><div class="line">\ No newline at end of file</div><div class="line">+Git is free software.</div><div class="line">+</div><div class="line">+add test add test</div><div class="line">\ No newline at end of file</div></pre></td></tr></table></figure>
<p>​</p>
</li>
<li><p>然后我们用<code>git status</code>查看一下状态：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">$ git status</div><div class="line">On branch master</div><div class="line">Your branch is ahead <span class="keyword">of</span> <span class="string">'origin/master'</span> by <span class="number">3</span> commits.</div><div class="line">  (use <span class="string">"git push"</span> to publish your local commits)</div><div class="line"></div><div class="line">Changes not staged <span class="keyword">for</span> commit:</div><div class="line">  (use <span class="string">"git add &lt;file&gt;..."</span> to update what will be committed)</div><div class="line">  (use <span class="string">"git checkout -- &lt;file&gt;..."</span> to discard changes <span class="keyword">in</span> working directory)</div><div class="line"></div><div class="line">        modified:   git.txt</div><div class="line"></div><div class="line">Untracked files:</div><div class="line">  (use <span class="string">"git add &lt;file&gt;..."</span> to include <span class="keyword">in</span> what will be committed)</div><div class="line"></div><div class="line">        test.txt</div></pre></td></tr></table></figure>
<p>Git非常清楚地告诉我们，<code>git.txt</code>被修改了，而<code>test.txt</code>还从来没有被添加过，所以它的状态是<code>Untracked</code></p>
</li>
<li><p>现在，使用两次命令<code>git add</code>，把<code>git.txt</code>和<code>test.txt</code>都添加后，用<code>git status</code>再查看一下：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">$ git status</div><div class="line">On branch master</div><div class="line">Your branch is ahead of 'origin/master' by 3 commits.</div><div class="line">  (use "git push" to publish your local commits)</div><div class="line">Changes to be committed:</div><div class="line">  (use "git reset HEAD &lt;file&gt;..." to unstage)</div><div class="line"></div><div class="line">        modified:   git.txt</div><div class="line">        new file:   test.txt</div></pre></td></tr></table></figure>
<p>所以，暂存区的状态就变成这样了：</p>
<p><img src="http://orj2jcr7i.bkt.clouddn.com/git%20add.png" alt="flex-axis"></p>
</li>
<li><p><code>git add</code>命令实际上就是把要提交的所有修改放到暂存区（Stage），然后，执行<code>git commit</code>就可以一次性把暂存区的所有修改提交到分支。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">$ git commit -m "updata&amp;test "</div><div class="line">[master 0fbc057] updata&amp;test</div><div class="line"> 3 files changed, 5 insertions(+), 1 deletion(-)</div><div class="line"> create mode 100644 test.txt</div></pre></td></tr></table></figure>
<p>在检查下状态，如果你没在对工作区文件进行修改的话，工作区返回的状态就是<code>clean</code></p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">$ git status</div><div class="line">On branch master</div><div class="line">Your branch is ahead of 'origin/master' by 4 commits.</div><div class="line">  (use "git push" to publish your local commits)</div><div class="line">nothing to commit, working tree clean</div></pre></td></tr></table></figure>
<p>现在版本库变成了这样，暂存区就没有任何内容了：</p>
<p><img src="http://orj2jcr7i.bkt.clouddn.com/git%20commit.png" alt="flex-axis"></p>
</li>
</ul>
<div class="tip"><br><br><strong>小结：</strong><br>暂存区是Git非常重要的概念，弄明白了暂存区，就弄明白了Git的很多操作到底干了什么!<br><br></div>

<h2 id="管理修改"><a href="#管理修改" class="headerlink" title="管理修改"></a>管理修改</h2><p>为什么Git比其他版本控制系统设计得优秀，因为Git跟踪并管理的是修改，而非文件。</p>
<p>每次修改，如果不<code>add</code>到暂存区，那就不会加入到<code>commit</code>中。</p>
<p><strong>例如：</strong></p>
<ul>
<li><p>我们对<code>git.txt</code>进行两次修改，并在修改之间进行如下指令操作：</p>
<p>第一次修改 -&gt; <code>git add</code> -&gt; 第二次修改 -&gt; <code>git commit</code>；</p>
<p>没错，我们会发现第二次修改没有被提交。我们前面讲了，Git管理的是修改，当你用<code>git add</code>命令后，在工作区的第一次修改被放入暂存区，准备提交，但是，在工作区的第二次修改并没有放入暂存区，所以，<code>git commit</code>只负责把暂存区的修改提交了，也就是第一次的修改被提交了，第二次的修改不会被提交。</p>
<p>​</p>
</li>
<li><p>那怎么提交第二次修改呢？你可以继续<code>git add</code>再<code>git commit</code>，也可以别着急提交第一次修改，先<code>git add</code>第二次修改，再<code>git commit</code>，就相当于把两次修改合并后一块提交了：</p>
<p>第一次修改 -&gt; <code>git add</code> -&gt; 第二次修改 -&gt; <code>git add</code> -&gt; <code>git commit</code></p>
<p><br></p>
</li>
</ul>
<p>注：提交后，用<code>git diff HEAD -- readme.txt</code>命令可以查看工作区和版本库里面最新版本的区别</p>
<h2 id="撤销修改"><a href="#撤销修改" class="headerlink" title="撤销修改"></a>撤销修改</h2><p>每个人都会犯错，但重点在于你能不能及时改正，Git当然也知道这一点，所以它给了我们撤销修改这个机会。</p>
<ul>
<li><p><strong>第一种情况，在没<code>git add</code>提交到暂存区时，撤销修改</strong></p>
<p>我对<code>git.txt</code>增加了一条错误信息，使用<code>git diff</code>查看一下：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"> $ git diff HEAD -- git.txt</div><div class="line">diff --git a/git.txt b/git.txt</div><div class="line">index a537f08..246dfe2 100644</div><div class="line">--- a/git.txt</div><div class="line">+++ b/git.txt</div><div class="line">@@ -4,4 +4,6 @@ Git is free software.</div><div class="line"> Git is a distributed version control system.</div><div class="line"> Git is free software.</div><div class="line"> add test add test</div><div class="line"></div><div class="line">+</div><div class="line">+Add an error message</div><div class="line">\ No newline at end of file</div></pre></td></tr></table></figure>
<p>我们再用<code>git status</code>查看一下状态：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">$ git status</div><div class="line">On branch master</div><div class="line">Your branch is ahead of 'origin/master' by 4 commits.</div><div class="line">  (use "git push" to publish your local commits)</div><div class="line">Changes not staged for commit:</div><div class="line">  (use "git add &lt;file&gt;..." to update what will be committed)</div><div class="line">  (use "git checkout -- &lt;file&gt;..." to discard changes in working directory)</div><div class="line"></div><div class="line">        modified:   git.txt</div><div class="line"></div><div class="line">no changes added to commit (use "git add" and/or "git commit -a")</div></pre></td></tr></table></figure>
<p>可以发现，Git会告诉你，<code>git checkout -- file</code>可以丢弃工作区的修改</p>
<p>ok， 我们试一下，执行：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ git checkout -- git.txt</div></pre></td></tr></table></figure>
<p>然后，查看文件<code>git.txt</code>:</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">$ cat git.txt</div><div class="line">Git is a version control system.</div><div class="line">Git is free software.</div><div class="line"></div><div class="line">Git is a distributed version control system.</div><div class="line">Git is free software.</div><div class="line"></div><div class="line">add test add test</div></pre></td></tr></table></figure>
<p>嗯，最后一行<code>Add an error message</code>果然撤销了</p>
<p>​</p>
</li>
<li><p><strong>第二种情况，你把修改文件提交到了暂存区，但在<code>git commit</code>之前</strong></p>
<p>我们给<code>git.txt</code>添加<code>Add a second error message</code>，并执行<code>git add</code>提交到暂存区，用<code>git staus</code>参看以下状态：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">$ $ git status</div><div class="line">  (use "git push" to publish your local commits)</div><div class="line">Changes to be committed:</div><div class="line">  (use "git reset HEAD &lt;file&gt;..." to unstage)</div><div class="line"></div><div class="line">        modified:   git.txt</div><div class="line">bash: $: command not found</div></pre></td></tr></table></figure>
<p>可以看到，Git同样告诉我们，用命令<code>git reset HEAD file</code>可以把暂存区的修改撤销掉（unstage），重新放回工作区：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">$ git reset HEAD git.txt</div><div class="line">Unstaged changes after reset:</div><div class="line">M       git.txt</div></pre></td></tr></table></figure>
<p><code>git reset</code>命令既可以回退版本，也可以把暂存区的修改回退到工作区。当我们用<code>HEAD</code>时，表示最新的版本。</p>
<p>现在，我们可以执行<code>git status</code>查看状态发现，暂存区是干净的，而工作区有修改，其实，现在就回到了我们上面<code>第一种情况</code>了，执行<code>git checkout -- git.txt</code>后，查看状态，发现工作区也干净了，也就达到撤销修改的目的了。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">$ cat git.txt</div><div class="line">Git is a version control system.</div><div class="line">Git is free software.</div><div class="line"></div><div class="line">Git is a distributed version control system.</div><div class="line">Git is free software.</div><div class="line"></div><div class="line">add test add test</div></pre></td></tr></table></figure>
</li>
</ul>
<div class="tip"><br><br><strong>小结:</strong><br><br>- 场景1：当你改乱了工作区某个文件的内容，想直接丢弃工作区的修改时，用命令git checkout – file。<br>- 场景2：当你不但改乱了工作区某个文件的内容，还添加到了暂存区时，想丢弃修改，分两步，第一步用命令git reset HEAD file，就回到了场景1，第二步按场景1操作。<br>- 场景3：已经提交了不合适的修改到版本库时，想要撤销本次提交，参考上一篇，不过前提是没有推送到远程库。<br><br></div>

<h2 id="删除文件"><a href="#删除文件" class="headerlink" title="删除文件"></a>删除文件</h2><p>在Git中，删除也是一个修改操作，我们实验一下，之前添加一个新文件test.txt到Git并且进行了<code>git commit</code>提交操作，可以看下<code>log</code>：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">$ git log --pretty=oneline</div><div class="line">0fbc057e11b4ba59f3700a79d760e5af927a6a65 updata&amp;test  //添加text.txt文件</div><div class="line">9152d920e48515d79a32824efcbe14b3665a3e6d add distributed</div><div class="line">f78f60960e2d59bd6fdc1a069e840c6d1f1c2566 add txt</div><div class="line">01ce8dd6733f7f78e7611ef72f2a092417de0bca updata homepage</div><div class="line">4db229de25fb4d0c325c98df9263b2c3d4d4607f add homepage</div><div class="line">6010c7e80796b40d89e1135bc2c86ac217274015 initial commit</div></pre></td></tr></table></figure>
<p>一般情况下，我们通常直接在文件管理器中把没用的文件删了，或者用<code>rm</code>命令删了：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">$ rm test.txt</div><div class="line"></div><div class="line"># 查看目录 已经没了test,txt文件</div><div class="line">$ ls</div><div class="line">git.txt  index.html  README.md</div></pre></td></tr></table></figure>
<p>习惯性查看下状态：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">$ git status</div><div class="line">On branch master</div><div class="line">Your branch is ahead of 'origin/master' by 4 commits.</div><div class="line">  (use "git push" to publish your local commits)</div><div class="line">Changes not staged for commit:</div><div class="line">  (use "git add/rm &lt;file&gt;..." to update what will be committed)</div><div class="line">  (use "git checkout -- &lt;file&gt;..." to discard changes in working directory)</div><div class="line"></div><div class="line">        deleted:    test.txt</div><div class="line"></div><div class="line">no changes added to commit (use "git add" and/or "git commit -a")</div></pre></td></tr></table></figure>
<p>发现Git已经知道我们进行了删除操作。</p>
<p><strong>现在会出现两种情况：</strong></p>
<ul>
<li><p>一种情况就是执行<code>rm</code>命令后，发现文件删除错误了，但好在版本库里还有，所以可以很轻松的把误删的文件恢复到最新版本：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ git checkout -- test.txt</div></pre></td></tr></table></figure>
<p><code>git checkout</code>其实是用版本库里的版本替换工作区的版本，无论工作区是修改还是删除，都可以“一键还原”。</p>
<p>​</p>
</li>
</ul>
<ul>
<li><p>另一种情况确定进行删除操作，并需要从版本库中删除该文件。因此，需要使用<code>git rm</code>命令，并执行<code>git commit</code>提交操作：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">$ git rm test.txt</div><div class="line">rm 'test.txt'</div><div class="line"></div><div class="line">$ git commit -m "deleted test"</div><div class="line">[master a15cd98] deleted test</div><div class="line"> 1 file changed, 0 insertions(+), 0 deletions(-)</div><div class="line"> delete mode 100644 test.txt</div></pre></td></tr></table></figure>
<p>现在，文件就从版本库中也删除了，就此消失不见~~~</p>
</li>
</ul>
<div class="tip"><br><br>命令git rm用于删除一个文件。如果一个文件已经被提交到版本库，那么你永远不用担心误删，但是要小心，你只能恢复文件到最新版本，你会丢失最近一次提交后你修改的内容。<br><br></div>

      
    </div>


    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/干货/" rel="tag">#干货</a>
          
            <a href="/tags/Git/" rel="tag">#Git</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/technology/other/Git实践-版本库控制/" rel="next" title="Git实践-版本库控制">
                <i class="fa fa-chevron-left"></i> Git实践-版本库控制
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/technology/other/如何制作一份优雅的简历/" rel="prev" title="LaTeX+ Sublime 制作一份优雅的简历">
                LaTeX+ Sublime 制作一份优雅的简历 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="hypercomments_widget"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      
      
        
          <ul class="sidebar-nav motion-element">
            <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
              Table of Contents
            </li>
            <li class="sidebar-nav-overview" data-target="site-overview">
              Overview
            </li>
          </ul>
        
      



      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="睡沙发的沙皮狗" />
          <p class="site-author-name" itemprop="name">睡沙发的沙皮狗</p>
           
              <p class="site-description motion-element" itemprop="description">睡沙发的沙皮狗 Leeifme</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">17</span>
                <span class="site-state-item-name">posts</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">categories</span>
              
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">tags</span>
              
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/leeifme" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/5406937103/profile?topnav=1&wvr=6" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  微博
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        

        


      </section>
      
        
        <!--noindex-->
          <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
            <div class="post-toc">

              
                
              

              
                <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#工作区和版本库"><span class="nav-number">1.</span> <span class="nav-text">工作区和版本库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#管理修改"><span class="nav-number">2.</span> <span class="nav-text">管理修改</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#撤销修改"><span class="nav-number">3.</span> <span class="nav-text">撤销修改</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除文件"><span class="nav-number">4.</span> <span class="nav-text">删除文件</span></a></li></ol></div>
              

            </div>
          </section>
        <!--/noindex-->
        
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">睡沙发的沙皮狗</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/zproo/hexo-blog">
    Next
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span></span>
  

  
    <span class="site-pv"><i class="fa fa-eye"> </i><span class="busuanzi-value" id="busuanzi_value_site_pv"></span></span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-ribbon/canvas-ribbon.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  





	

		<script type="text/javascript">
		_hcwp = window._hcwp || [];

		_hcwp.push({widget:"Bloggerstream", widget_id: 92841, selector:".hc-comment-count", label: "{\%COUNT%\}" });

		
		_hcwp.push({widget:"Stream", widget_id: 92841, xid: "technology/other/Git实践-修改操作/"});
		

		(function() {
		if("HC_LOAD_INIT" in window)return;
		HC_LOAD_INIT = true;
		var lang = (navigator.language || navigator.systemLanguage || navigator.userLanguage || "en").substr(0, 2).toLowerCase();
		var hcc = document.createElement("script"); hcc.type = "text/javascript"; hcc.async = true;
		hcc.src = ("https:" == document.location.protocol ? "https" : "http")+"://w.hypercomments.com/widget/hc/92841/"+lang+"/widget.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(hcc, s.nextSibling);
		})();
		</script>

	







  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').fadeToggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ decodeURIComponent(data_url) +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });

                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').fadeOut(function() {
          $(".popoverlay").remove();
          $('body').css('overflow', '');
      });
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("6mFxqINb4RcjTGhNbtCzfWI1-gzGzoHsz", "c4qK91bIu9qFdGeimnKdriiK");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" async src="//push.zhanzhang.baidu.com/push.js">
</script>


</body>
</html>
